/**
 * Word报告导出组件
 * 提供将计算结果导出为Word文档的功能，支持多种导出选项
 * 封装Ant Design的Button和Dropdown组件，实现友好的用户交互体验
 */
import React, { useState } from 'react';
import { Button, Dropdown } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { transformInputsWithNamesAndUnits } from '../utils/parameterMappings';
import notificationService from '../../services/notificationService';
import errorHandlerService from '../../services/errorHandlerService';
import { safeInvoke } from '../utils/ipcUtils';

/**
 * Word报告导出组件属性接口
 */
interface SaveWordReportProps {
  /** 站点名称，用作报告标题前缀 */
  siteName?: string;
  /** 计算输入参数 */
  inputs?: Record<string, any>;
  /** 计算结果数据 */
  results?: Record<string, any>;
  /** 报告作者信息 */
  author?: string;
  /** 自定义子组件，默认不显示 */
  children?: React.ReactNode;
  /** 计算类型，用于参数映射转换 */
  calculationType?: string;
}

/**
 * Word报告导出组件实现
 * 调用后端IPC `perform-calculation` 的 `export-report-docx` 功能导出报告
 */
const SaveWordReport: React.FC<SaveWordReportProps> = ({
  siteName = '计算报告',
  inputs = {},
  results = {},
  author = '',
  children,
  calculationType = '',
}) => {
  // 导出按钮加载状态
  const [loading, setLoading] = useState<boolean>(false);

  /**
   * 执行Word报告导出
   * @param suffix - 文件名后缀，通常是时间戳
   * @param openFile - 是否导出后自动打开文件
   */
  const doExport = async (suffix?: string, openFile = false): Promise<void> => {
    try {
      setLoading(true);
      
      // 支持添加时间戳后缀构建报告名称
      const reportName = suffix 
        ? `${siteName}_${suffix}` 
        : siteName;
      
      // 转换输入参数为带中文名称和单位的对象，提升报告可读性
      const transformedInputs = transformInputsWithNamesAndUnits(inputs, calculationType);
      
      // 使用安全的IPC调用进行报告导出
      const resp = await safeInvoke<{ success: boolean; data?: string; error?: string }>(
        'perform-calculation',
        {
          calculationType: 'export-report-docx',
          params: {
            siteName: reportName,
            inputs: transformedInputs,
            results,
            author,
            openFile,
          },
        },
        true // 显示错误通知
      );
      
      if (resp && resp.success) {
        notificationService.success(`已成功导出Word报告: ${reportName}`);
      } else {
        throw new Error(resp?.error || '导出失败');
      }
    } catch (error) {
      console.error('Word报告导出失败:', error);
      // 错误处理已由safeInvoke完成
    } finally {
      setLoading(false);
    }
  };

  /**
   * 生成导出菜单选项
   */
  const menuItems: MenuProps['items'] = [
    {
      key: 'now',
      label: '现在导出',
      onClick: () => doExport(),
    },
    {
      key: 'withTime',
      label: '带时间戳导出',
      onClick: () => {
        const timestamp = new Date()
          .toISOString()
          .replace(/[:.]/g, '-')
          .substring(0, 19);
        doExport(timestamp);
      },
    },
    {
      key: 'withTimeAndOpen',
      label: '带时间戳导出并打开',
      onClick: () => {
        const timestamp = new Date()
          .toISOString()
          .replace(/[:.]/g, '-')
          .substring(0, 19);
        doExport(timestamp, true);
      },
    },
  ];

  return (
    <>
      {children || (
        <Dropdown menu={{ items: menuItems }} trigger={['click']}>
          <Button
            type="primary"
            size="middle"
            loading={loading}
            icon={<DownOutlined />}
            style={{ marginLeft: 8 }}
            className="word-export-button"
          >
            导出Word报告
          </Button>
        </Dropdown>
      )}
    </>
  );
};

export default SaveWordReport;